package com.tcsl.mylibrary;

import android.content.Context;
import android.content.Intent;

import com.google.gson.Gson;
import com.ums.AppHelper;

import java.util.Map;

import cn.com.tcsl.canyin7.pay.ums.UmsBusinessCategory;
import cn.com.tcsl.canyin7.pay.ums.UmsBusinessUtils;
import cn.com.tcsl.canyin7.pay.ums.UmsQmhResult;

/**
 * 描述:银联支付
 * <p/>作者：wjx
 * <p/>创建时间: 2017/5/26 16:44
 */
public class PayUMS extends TcslPay {
    /**
     * 银联商务刷卡requestCode
     */
    private static final int PAY_UMS = AppHelper.TRANS_REQUEST_CODE;

    public PayUMS(Context context) {
        super(context);
    }

    @Override
    protected void pay(Float money, String orderNo, String merchantNo) {
        UmsBusinessUtils.qmhConsume(mActivity, (int) (money * 100));
    }

    @Override
    public boolean onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == PAY_UMS) {
            String reason = "交易失败，请重试！";
            Map<String, String> map = null;
            //A8机型有bug，取消交易后，有时AppHelper.filterTransResult(data)报空指针异常，需要处理
            try {
                map = AppHelper.filterTransResult(data);
            } catch (NullPointerException e) {
                e.printStackTrace();
                mListener.payError(reason);
                return true;
            }
            //大类
            String appName = map.get(AppHelper.TRANS_APP_NAME);
            //返回码
            int appResultCode = Integer.parseInt(map.get(AppHelper.RESULT_CODE));
            //如果返回码为调用成功
            switch (appResultCode) {
                //如果成功
                case 0x00:
                    //全民惠
                    if (appName.equals(UmsBusinessCategory.QMH)) {
                        String transData = map.get(AppHelper.TRANS_DATA);
                        Gson gson = new Gson();
                        UmsQmhResult qmhResult = gson.fromJson(transData, UmsQmhResult.class);
                        //交易成功
                        if ("交易成功".equals(qmhResult.getResDesc())) {
                            mListener.paySuccess("全民惠支付成功", "");
                        } else {//交易不成功（多种原因）
                            reason = qmhResult.getResDesc();
                            mListener.payError(reason);
                        }
                    }
                    break;
                default:
                    mListener.payError(reason);
                    break;
            }
            return true;
        } else {
            return false;
        }
    }
}
